package cn.tedu.charging.order.mqtt;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class MqttProducerClient {
    @Autowired
    private MqttClient mqttClient;
    //1.默认发送,指定主题名称,消息对象,qos=1,retained=true
    public void send(String destination,Object msg){
        this.send(destination,msg,1,true);
    }
    //2.指定发送,提供主题名,消息对象,qos,retained
    public void send(String destination,Object msg,int qos,boolean retained){
        //需要先对msg做序列化 json做序列化
        String jsonData = JSON.toJSONString(msg);
        byte[] payload = jsonData.getBytes(StandardCharsets.UTF_8);
        try{
            mqttClient.publish(destination,payload,qos,retained);
        }catch (Exception e){
            log.error("发送消息失败",e);
        }
    }
}
